from flask import Blueprint, request, jsonify
import json, os

from db import db1

bp_course = Blueprint('course', __name__)


def get_data():
    data = request.data
    if data:
        data = json.loads(data)
    else:
        data = request.form
    return data


# 无限级分类重构
def xtree(data):
    # 先判断data没有直接返回
    if not data:
        return data
    # 遍历data变成字典
    tree = {}
    list = []
    for i in data:
        tree[i['id']] = i

    for j in data:
        # 获取父id
        pid = j['pid']
        if pid == 0:
            # 说明顶级分类直接加入列表
            list.append(j)
        else:
            # 查看父类下有没有子类
            if 'son' not in tree[pid]:
                # 如果没有初始化列表
                tree[pid]['son'] = []
            # 把子类加到父类列表中
            tree[pid]['son'].append(j)
    return list


@bp_course.route('/cateM', methods=['POST', 'GET'])
def cateM():
    if request.method == 'POST':
        # 添加
        # 获取数据
        data = get_data()
        print(data)
        # 构造sql
        if data['params']:
            sql = "insert into cates values(0,'%s',%d,%s)" % (data['name'], int(data['pid']), data['params'])
        else:
            sql = "insert into cates(name,pid) values('%s',%d)" % (data['name'], int(data['pid']))
        # 调用db1
        db1.update(sql)
        # 返回结果
        return jsonify({"code": 200})
    else:
        # 无限级分类展示
        sql = "select * from cates"
        res = db1.find_all(sql)
        data = xtree(res)
        return jsonify({"code": 200, 'list': data})


@bp_course.route('/pagecates')
def pagecates():
    # 每页面显示多少条
    page_size = 2
    # 当前页
    page = request.args.get('page')
    start = (int(page) - 1) * page_size
    sql = "select * from cates  order by id asc limit %d,%d" % (start, page_size)
    # sql = "select c.name,c.params,t.name as tname from cates as c left join cates as t on c.pid=t.id order by c.id desc"
    res = db1.find_all(sql)
    # 查询共有多少条记录
    sql1 = "select count(id) as total from cates"
    res1 = db1.find(sql1)
    return jsonify({"code": 200, 'list': res, 'total': res1['total']})


# 通过分类id获取分类参数
@bp_course.route('/getCateByid')
def getCateByid():
    id = request.args.get('id')
    sql = "select params from cates where id=%d" % (int(id))
    res = db1.find(sql)
    return jsonify({'code': 200, 'params': res['params']})



# 添加展示课程接口
@bp_course.route('/courseM', methods=['POST', 'GET'])
def courseM():
    if request.method == "POST":
        data = get_data()
        if data['params']:
            sql = "insert into courses values(0,'%s',%d,'%s','%s','%s',%d,%d)" % (
                data['title'], int(data['pid']), data['params'], data['pic'], data['descrip'], int(data['teacher_id']),
                int(data['status']))
        else:
            sql = "insert into courses(title,pid,pic,descrip,teacher_id,status) values('%s',%d,'%s','%s',%d,%d)" % (
                data['title'], int(data['pid']), data['pic'], data['descrip'], int(data['teacher_id']),
                int(data['status']))

        db1.update(sql)
        return jsonify({"code": 200})
    else:
        # 分页获取所有数据
        # 获取当前页
        page = request.args.get('page')
        # 定义每页显示多少条
        page_size = 2
        # 计算开始下标
        start = (int(page) - 1) * page_size
        # 构造sql
        sql = "select c.title,c.pic,ca.name from courses as c left join cates as ca on c.pid=ca.id limit %d,%d" % (
            start, page_size)
        res = db1.find_all(sql)
        # 查询共有多少条
        sql1 = "select count(id) as count from courses"
        total = db1.find(sql1)
        return jsonify({"code": 200, 'list': res, 'total': total['count']})


# 视频上传
@bp_course.route('/vedioUpload', methods=['POST'])
def vedioUpload():
    # 获取要上传的文件流，课程id
    file = request.files['file']
    course_id = request.form['course_id']
    # 判断文件夹是否存在，如果没有，创建文件夹
    path = './upload/' + str(course_id)
    if not os.path.exists(path):
        os.mkdir(path)
    # 上传文件到指定文件夹
    file.save(os.path.join(path, file.filename))
    # 返回结果
    return jsonify({"code": 200, 'url': path + '/' + file.filename})


# 添加章节接口
@bp_course.route('/jieM', methods=['POST', 'GET'])
def jieM():
    if request.method == "POST":
        data = get_data()
        sql = "insert into jie values(0,'%s',%d,'%s')" % (data['name'], int(data['course_id']), data['vedio_url'])
        db1.update(sql)
        return jsonify({"code": 200})
    else:
        # 获取章节列表必须传入课程id
        course_id = request.args.get('cid')
        if not course_id:
            return jsonify({"code": 10010, 'mes': '必须传入课程id才能获取章节信息'})
        sql = "select * from jie where course_id=%d order by sort asc" % (int(course_id))
        res = db1.find_all(sql)
        return jsonify({"code": 200, 'list': res})


